package goodbaby.dklt.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.classic.core.activity.BaseActivity;
import com.classic.core.utils.NetworkUtil;
import com.classic.core.utils.StringUtil;
import com.classic.core.utils.ToastUtil;
import com.classic.okhttp.gbb.http.ActionHelp;
import com.classic.okhttp.gbb.http.ObjectCallback;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.LinkedHashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import goodbaby.dklt.GbbCache;
import goodbaby.dklt.GbbPreferences;
import goodbaby.dklt.R;
import goodbaby.dklt.bean.LoginInfo;

/**
 * Created by Jayden on 2016/4/25 15:47.
 *
 * @version V1.0
 * @Title: LoginActivity
 * @Description: 登录页面
 */
public class LoginActivity extends BaseActivity {

    private String account = "";
    private Button btnLogin;
    private CheckBox cbAutoLogin;
    private EditText etPsd;
    private AutoCompleteTextView etUserName;
    private ImageView ivClearPsd;
    private ImageView ivClearUserName;
    private String pwd = "";
    private TextView tvForget;

    private void setEnable(boolean paramBoolean) {
        etUserName.setEnabled(paramBoolean);
        etPsd.setEnabled(paramBoolean);
        cbAutoLogin.setEnabled(paramBoolean);
        tvForget.setEnabled(paramBoolean);
        btnLogin.setEnabled(paramBoolean);
        btnLogin.setText(paramBoolean ? "登录" : "正在登录...");
    }

    void checkLogin() {
        this.account = this.etUserName.getText().toString();
        this.pwd = this.etPsd.getText().toString();
        if (StringUtil.isEmpty(this.account)) {
            ToastUtil.showToast(this, "请输入帐号");
            return;
        }
        if (StringUtil.isEmpty(this.pwd)) {
            ToastUtil.showToast(this, "请输入密码");
            return;
        }
        if (StringUtil.isMobile(this.account)) {
            setEnable(false);
            ActionHelp.userLogin(this, this.account, this.pwd, new ObjectCallback<LoginInfo>() {

                public void onError(int paramAnonymousInt) {
                    LoginActivity.this.setEnable(true);
                    if (paramAnonymousInt == 303) {
                        ToastUtil.showToast(LoginActivity.this, "用户名或密码错误");
                    } else if (paramAnonymousInt == 302) {
                        ToastUtil.showToast(LoginActivity.this, "用户名或密码不能为空");
                    }
                }

                public void onError(int paramAnonymousInt, String paramAnonymousString) {
                    super.onError(paramAnonymousInt, paramAnonymousString);
                    LoginActivity.this.setEnable(true);
                    if (paramAnonymousInt == 303)
                        ToastUtil.showToast(LoginActivity.this, "用户名或密码错误");
                    while (paramAnonymousInt != 302)
                        return;
                    ToastUtil.showToast(LoginActivity.this, "用户名或密码不能为空");
                }

                public void onHttpError(int paramAnonymousInt) {
                    super.onHttpError(paramAnonymousInt);
                    ToastUtil.showToast(LoginActivity.this, "请求超时");
                    setEnable(true);
                }

                public void onSuccess(LoginInfo loginInfo) {
                    if (cbAutoLogin.isChecked()) {
                        cbAutoLogin.setChecked(true);
                        GbbPreferences.saveKeepLogin("y");
                    } else {
                        cbAutoLogin.setChecked(false);
                        GbbPreferences.saveKeepLogin("n");
                    }
                    GbbCache.setAccount(account);
                    GbbCache.setPassword(pwd);
                    GbbPreferences.saveUserAccount(account);
                    GbbPreferences.saveUserPwd(pwd);
                    GbbPreferences.saveBraceletAddress(loginInfo.getBraceletAddress());
                    GbbPreferences.saveSchoolName(loginInfo.getSchoolName());
                    GbbPreferences.saveClassName(loginInfo.getClassName());
                    GbbPreferences.saveClassId(StringUtil.getNumber(loginInfo.getClassId()));
                    GbbPreferences.saveClassTeacherId(loginInfo.getClassTeacherID());
                    GbbPreferences.saveHeight(loginInfo.getHeight());
                    GbbPreferences.saveBirthday(loginInfo.getBirthday());
                    GbbPreferences.saveName(loginInfo.getName());
                    GbbPreferences.saveAdminId(loginInfo.getAdminId());
                    GbbPreferences.saveWeight(loginInfo.getWeight());
                    GbbPreferences.saveSex(loginInfo.getSex());
                    GbbPreferences.saveRole(loginInfo.getRoleId() + "");
                    if (!StringUtil.isEmpty(loginInfo.getSObject()))
                        GbbPreferences.saveSObject(loginInfo.getSObject());
                    if (!StringUtil.isEmpty(loginInfo.getImagePath()))
                        GbbPreferences.saveHeadImg(loginInfo.getImagePath());
                    Set<String> tagSet = new LinkedHashSet<String>();
                    tagSet.add(loginInfo.getClassId());
                    tagSet.add(loginInfo.getSchoolId());
                    JPushInterface.setAliasAndTags(getApplicationContext(), loginInfo.getAdminId(), tagSet, new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set<String> set) {
                            Log.e("JPushS", i + "");
                            Log.e("JPushA", s);
                            Log.e("JPushT", set.toString());
                        }
                    });

                    toMainActivity();
                }

                @Override
                public Type getType() {
                    return new TypeToken<LoginInfo>() {
                    }.getType();
                }
            });
        } else {
            ToastUtil.showToast(this, "请输入正确的帐号");
            setEnable(true);
        }
    }

    void clickLogin() {
        if (NetworkUtil.isNetworkConnected(this)) {
            checkLogin();
        } else {
            ToastUtil.showToast(this, "网络未连接，请检查网络设置");
        }
    }

    public int getLayoutResId() {
        return R.layout.activity_login;
    }

    public void initLoginData() {
        super.initData();
        account = GbbPreferences.getUserAccount();
        pwd = GbbPreferences.getUserPwd();
        if (account != null) {
            etUserName.setText(account);
            ivClearUserName.setVisibility(View.VISIBLE);
            String str = GbbPreferences.getKeepLogin();
            if (str == null) {
                str = "n";
            }
            if (str.equals("y")) {
                cbAutoLogin.setChecked(true);
                etPsd.setText(pwd);
                ivClearPsd.setVisibility(View.VISIBLE);
            } else {
                cbAutoLogin.setChecked(false);
                etPsd.setText("");
            }
        } else {
            etUserName.setText("");
            etPsd.setText("");
        }
    }

    public void initView() {
        super.initView();
        etUserName = (AutoCompleteTextView) findViewById(R.id.login_user_et);
        etPsd = (EditText) findViewById(R.id.login_pwd_et);
        ivClearUserName = (ImageView) findViewById(R.id.login_user_clear_iv);
        ivClearUserName.setOnClickListener(this);
        ivClearUserName.setVisibility(View.GONE);
        ivClearPsd = (ImageView) findViewById(R.id.login_pwd_clear_iv);
        ivClearPsd.setOnClickListener(this);
        ivClearPsd.setVisibility(View.GONE);
        btnLogin = (Button) findViewById(R.id.login_btn);
        btnLogin.setOnClickListener(this);
        tvForget = (TextView) findViewById(R.id.login_tv_forgetpwd);
        tvForget.setOnClickListener(this);
        cbAutoLogin = (CheckBox) findViewById(R.id.login_cb_auto);
        initLoginData();
        etUserName.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable paramAnonymousEditable) {
                if (StringUtil.isEmpty(etUserName.getText().toString())) {
                    ivClearUserName.setVisibility(View.GONE);
                    etPsd.setText("");
                } else {
                    LoginActivity.this.ivClearUserName.setVisibility(View.VISIBLE);
                }
            }

            public void beforeTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) {
            }

            public void onTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) {
            }
        });
        this.etPsd.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable paramAnonymousEditable) {
                if (StringUtil.isEmpty(etPsd.getText().toString())) {
                    LoginActivity.this.ivClearPsd.setVisibility(View.GONE);
                } else {
                    LoginActivity.this.ivClearPsd.setVisibility(View.VISIBLE);
                }
            }

            public void beforeTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) {
            }

            public void onTextChanged(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) {
            }
        });
    }

    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
    }

    protected void onDestroy() {
        super.onDestroy();
    }

    protected void onResume() {
        super.onResume();
    }

    void toMainActivity() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    public void viewClick(View paramView) {
        super.viewClick(paramView);
        switch (paramView.getId()) {
            default:
                break;
            case R.id.login_btn:
                clickLogin();
                break;
            case R.id.login_user_clear_iv:
                this.etUserName.setText("");
                this.ivClearUserName.setVisibility(View.GONE);
                break;
            case R.id.login_pwd_clear_iv:
                this.etPsd.setText("");
                this.ivClearPsd.setVisibility(View.GONE);
                break;
            case R.id.login_tv_forgetpwd:
                startActivity(new Intent(this, ForgetActivity.class));
                break;
        }

    }
}
